package main

import (
	"bufio"
	"github.com/astaxie/beego/logs"
	"net"
	"os"
	"strings"
)

//全局变量
var (
	//全局日志
	log *logs.BeeLogger
)

//日志配置
func init() {
	//创建logger对象
	log = logs.NewLogger()
	//log输出到控制台
	log.SetLogger(logs.AdapterConsole)
	//log输出的文件
	log.SetLogger(logs.AdapterFile, `{"filename":"./logs/client.log" ,"level":6,"maxlines":0,"maxsize":0,"daily":true,"maxdays":1}`)
}
func main() {
	conn, e := net.Dial("tcp", ":9000")
	checkErr(e, "handle")
	defer conn.Close()
	//读写分离的搞
	//读数据
	go func() {
		for {
			data := make([]byte, 1<<10)
			log.Info(">>>>start read data length=%d", len(data))
			n, err := conn.Read(data)
			if err != nil {
				log.Info("client err=%v", err)
				break
			}
			//有数据就展示 ，没有就不展示，执行写的逻辑
			if n > 0 {
				log.Info("receive data=" + string(data[:n]))
			}
		}
	}()
	//写数据
	go func() {
		for {
			reader := bufio.NewReader(os.Stdin)
			s, err := reader.ReadString('\n')
			if err != nil {
				log.Info("read console err=%v", err)
			}
			s = strings.Replace(s, "\r\n", "", -1)
			conn.Write([]byte(s))
		}
	}()
	select {}
	//连接之后的事情
	/*
		for {
			data := make([]byte, 1<<10)
			log.Info("data length=%d", len(data))
			n, err := conn.Read(data)
			if err != nil {
				log.Info("client err=%v", err)
				break
			}
			//有数据就展示 ，没有就不展示，执行写的逻辑
			if n > 0 {
				log.Info("receive data=" + string(data[:n]))
			}
			//tmp := make([]byte, 1<<10)
			//n, err = os.Stdin.Read(tmp)
			//if err != nil {
			//	log.Info("write err=%v", err)
			//}
			reader := bufio.NewReader(os.Stdin)
			s, err := reader.ReadString('\n')
			if err != nil {
				log.Info("read console err=%v", err)
			}
			s = strings.Replace(s, "\r\n", "", -1)
			conn.Write([]byte(s))

			//log.Info("%v", 1<<11)
		}
	*/
}
func checkErr(err error, mes string) {
	if err != nil {
		log.Info(mes+",err=", err)
		return
	}
}
